/*
 * TimePerformanceInterceptor.java    ver   29/nov/2009
 *
 * Copyright (c) 2009 mentalsmash.org
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * The use of the Apache License does not indicate that this project is
 * affiliated with the Apache Software Foundation.
 */
package org.mentalsmash.tazio.commons.timer;

import java.util.Date;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @version 0.0.1 29/nov/2009
 * @author Andrea Reale <andrea.reale@gmail.com>
 * 
 */
class TimePerformanceInterceptor implements MethodInterceptor {
    private final Logger log = LoggerFactory
	    .getLogger(TimePerformanceInterceptor.class);
    private final TimingsLog timeLog;

    TimePerformanceInterceptor(final TimingsLog tlog) {
	timeLog = tlog;
    }

    /*
     * (non-Javadoc)
     * 
     * @see
     * org.aopalliance.intercept.MethodInterceptor#invoke(org.aopalliance.intercept
     * .MethodInvocation)
     */
    @Override
    public Object invoke(final MethodInvocation invocation) throws Throwable {
	final Date startedInvocation = new Date();
	long duration;

	final Object retVal = invocation.proceed();
	duration = System.currentTimeMillis() - startedInvocation.getTime();
	if (duration < 0) {
	    log.error("Invalid duartion: {}, on method invocation {}",
		    duration, invocation.getMethod());
	} else if (duration == 0) {
	    log.debug("Duration was 0, setting to 1");
	    duration = 1;
	}
	final String key = invocation.getMethod().getDeclaringClass().getName()
		+ "#" + invocation.getMethod().getName();
	timeLog.addTimingMeasure(key, duration);
	return retVal;
    }
}
